package io.renren.modules.user.service.impl;

import io.renren.common.exception.RRException;
import io.renren.common.utils.ConstantUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.modules.dictionary.dao.DictionaryDao;
import io.renren.modules.dictionary.entity.DictionaryEntity;
import io.renren.modules.feedback.entity.FeedbackinfosEntity;
import io.renren.modules.user.dao.UserinfosDao;
import io.renren.modules.user.util.UserUtil;
import io.renren.modules.vipuser.dao.VipinfosDao;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import io.renren.modules.user.entity.UserinfosEntity;
import io.renren.modules.user.service.UserinfosService;



/**
 * @author 杨帅
 */
@Service("userinfosService")
public class UserinfosServiceImpl implements UserinfosService {
	@Autowired
	private UserinfosDao userinfosDao;
	@Autowired
	private DictionaryDao dictionaryDao;
	@Autowired
	private VipinfosDao vipinfosDao;


	@Override
	public List<UserinfosEntity> queryDescList(Map<String, Object> map) {
		return userinfosDao.queryDescList(map);
	}

	@Override
	public int queryDescTotal(Map<String, Object> map) {
		return userinfosDao.queryDescTotal(map);
	}

	@Override
	public int uploadIcon(Map<String, Object> map) {
		return userinfosDao.uploadIcon(map);
	}

	@Override
	public UserinfosEntity queryObject(String userinfoid){
		//返回用户数据前先进行用户身份状态设置
		boolean isVip = UserUtil.isvip(vipinfosDao,userinfosDao,userinfoid);
		UserinfosEntity userinfosEntity = userinfosDao.queryObject(userinfoid);
		//清空密码
		userinfosEntity.setUserpwd(null);
		return userinfosEntity;
	}
	
	@Override
	public List<UserinfosEntity> queryList(Map<String, Object> map){
		List<UserinfosEntity> oldUserinfosEntities = userinfosDao.queryList(map);
		for (UserinfosEntity oldUserinfosEntity : oldUserinfosEntities) {
			UserUtil.isvip(vipinfosDao, userinfosDao, oldUserinfosEntity.getUserinfoid());
		}
		List<UserinfosEntity> newUserinfosEntities = userinfosDao.queryList(map);
		return newUserinfosEntities;
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return userinfosDao.queryTotal(map);
	}
	
	@Override
	public void save(UserinfosEntity userinfos){
		Date now = new Date();
		//密码sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		userinfos.setUserpwd(new Sha256Hash(userinfos.getUserpwd(), salt).toHex().toString());
		userinfos.setSalt(salt);
		//补充用户数据
		//产生UUID主键
		userinfos.setUserinfoid(UUID.randomUUID().toString().replaceAll("-",""));
		//产生注册时间
		userinfos.setCreatetime(now);
		//产生密码更新时间
		userinfos.setLastpasswordchangeddate(now);
		//产生更新信息的时间
		userinfos.setUpdatetime(now);
		//补充用户是否为VIP 0为普通用户,1为VIP用户
		userinfos.setIsvip(ConstantUtils.COMMON);
		//查询字典获取原始数据
		List<DictionaryEntity> passwordErrorFieldManagement = dictionaryDao.searchByTypename("PasswordErrorFieldManagement");
		//数据处理
		Map<String, Object> passwordErrorField = UserUtil.passwordErrorFieldDictionaryInformationProcessing(passwordErrorFieldManagement);
		userinfos.setFailedpasswordattemptcount((Integer) passwordErrorField.get("UserFailedPasswordAttemptCount"));
		//为空补充初始积分
		if (userinfos.getIntegralnumber() == null){
			List<DictionaryEntity> initialPoints = dictionaryDao.searchByTypename("InitialPoints");
			String initialIntegration = UserUtil.initialIntegrationProcessing(initialPoints);
			userinfos.setIntegralnumber(new BigDecimal(initialIntegration));
		}
		//插入用户数据
		userinfosDao.save(userinfos);
	}
	
	@Override
	public void update(UserinfosEntity userinfos){
		//修改更新信息时间
		userinfos.setUpdatetime(new Date());
		//判断密码是否发生改变
		UserinfosEntity userinfosEntity = userinfosDao.queryObject(userinfos.getUserinfoid());

		if (StringUtils.isBlank(userinfos.getUserpwd())){
			userinfos.setUserpwd(null);
		}else{
				//填充密码更新时间
				userinfos.setLastpasswordchangeddate(new Date());
				String salt = RandomStringUtils.randomAlphanumeric(20);
				String newPassword = new Sha256Hash(userinfos.getUserpwd(), salt).toHex().toString();
				userinfos.setUserpwd(newPassword);
				userinfos.setSalt(salt);
		}
		//用户账户不可更改
		userinfos.setUseraccount(userinfosEntity.getUseraccount());
		userinfosDao.update(userinfos);
	}
	
	@Override
	public void delete(String userinfoid){
		userinfosDao.delete(userinfoid);
	}
	
	@Override
	public void deleteBatch(String[] userinfoids){
		userinfosDao.deleteBatch(userinfoids);
	}

	@Override
	public int isUserAccountRepetition(String userAccount) {
		return userinfosDao.isUserAccountRepetition(userAccount);
	}

	@Override
	public List<UserinfosEntity> queryUserByName(Map<String, Object> map) {
		//返回用户数据前先进行用户身份状态设置
		List<UserinfosEntity> oldUserinfosEntities = userinfosDao.queryUserByName(map);
		for (UserinfosEntity oldUserinfosEntity : oldUserinfosEntities) {
			UserUtil.isvip(vipinfosDao, userinfosDao, oldUserinfosEntity.getUserinfoid());
		}
		List<UserinfosEntity> newUserinfosEntities = userinfosDao.queryUserByName(map);
		return newUserinfosEntities;
	}

	@Override
	public int queryUserByNameTotal(Map<String, Object> map) {
		return userinfosDao.queryUserByNameTotal(map);
	}

	@Override
	public int isUserIdExist(String userinfoid) {
		return userinfosDao.isUserIdExist(userinfoid);
	}

	@Override
	public String login(String useraccount, String userpwd) {
        UserinfosEntity user = userinfosDao.login(useraccount);
        Assert.isNull(user, "账户或密码错误");
		String password = new Sha256Hash(userpwd, user.getSalt()).toHex();
        //密码错误
        if(!user.getUserpwd().equals(password)){
			throw new RRException("账户或密码错误");
        }

        if (user.getIslockedout() == ConstantUtils.LOCKEDOUT){
			throw new RRException("账户已锁定");
		}

        return user.getUserinfoid();
	}

	@Override
	public UserinfosEntity queryUserinfo(String userinfoid) {
		//返回用户数据前先进行用户身份状态设置
		boolean isVip = UserUtil.isvip(vipinfosDao,userinfosDao,userinfoid);
		return userinfosDao.queryUserinfo(userinfoid);
	}

	/**
	 * @methodName reduceTheIntegral
	 * @param userinfoid
	 * @param cull 要减少积分的数量
	 * @throws Exception
	 * @return boolean
	 * @author 杨帅
	 * @date 2018/11/1 23:04
	 * 积分减少方法
	 */
	@Override
	public boolean reduceTheIntegral(String userinfoid,BigDecimal cull) {
		UserinfosEntity userinfosEntity = userinfosDao.queryUserinfo(userinfoid);
		BigDecimal integralNumber =  userinfosEntity.getIntegralnumber().subtract(cull);
		if (integralNumber.compareTo(ConstantUtils.MININTEGRALNUMBER) >= 0){
			UserinfosEntity newUser = new UserinfosEntity();
			newUser.setIntegralnumber(integralNumber);
			newUser.setUserinfoid(userinfoid);
			userinfosDao.update(newUser);
			return true;
		}
		return false;
	}

	@Override
	public UserinfosEntity queryUserByAccount(String userAccount) {
		return userinfosDao.queryUserByAccount(userAccount);
	}

	@Override
	public void updateApiUser(UserinfosEntity entity) {
		userinfosDao.updateApiUser(entity);
	}

	@Override
	public R judgeIsDelError(int code) {
		if(code != ConstantUtils.DEL && code != ConstantUtils.DELED){
			return R.error("软删除状态码错误!");
		}
		return null;
	}

	@Override
	public R judgeIsVipError(int code) {
		if(code != ConstantUtils.VIP && code != ConstantUtils.COMMON){
			return R.error("VIP状态码错误!");
		}
		return null;
	}

	@Override
	public R judgeIslockedoutError(int code) {
		if(code != ConstantUtils.LOCKEDOUT && code != ConstantUtils.NOTLOCKEDOUT){
			return R.error("锁定状态码错误!");
		}
		return null;
	}

	@Override
	public R judgeIsUsergenderError(int code) {
		if(code != ConstantUtils.MAN && code != ConstantUtils.WOMAN){
			return R.error("性别状态码错误!");
		}
		return null;
	}

	@Override
	public boolean isVip(String userinfoid) {
		return UserUtil.isvip(vipinfosDao,userinfosDao,userinfoid);
	}

	@Override
	public UserinfosEntity queryPasswordInfo(String userinfoid) {
		return userinfosDao.queryPasswordInfo(userinfoid);
	}

	@Override
	public UserinfosEntity queryApiIntegralNumber(String userinfoid) {
		return userinfosDao.queryApiIntegralNumber(userinfoid);
	}


	@Override
	public R judgeUserError(String userinfoid){
		if(userinfosDao.isUserIdExist(userinfoid) == 0){
			return R.error("用户不存在！");
		}
		return null;
	}



}
